package org.grow.yc.filter;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.grow.yc.service.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @Author: xwg
 * @CreateDate: 2024/9/29
 */

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtService jwtService;
    //    钩子函数 守卫函数
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
//        return true 代表放行
//        return false代表拦截不放行返回

        String authorization = request.getHeader("authorization");

//        String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
//        if(StringUtils.hasText(authorization))
        if (authorization == null || authorization.equals("")) {
            System.out.println("401 没登录 不能访问" + request.getRequestURI());
            response.setStatus(401);
            response.getWriter().println("please login first to access " + request.getRequestURI());
            return false;
        } else {
            System.out.println("登录了 interceptor: " + request.getRequestURI());
            System.out.println("已经登录" + authorization);
//            身份认证的主要意义在于增强不是拦截
//            根据token 解析 出当前登录人的UID
            String pure_token = authorization.replace("Bearer", "").trim();
// 此处应该进行Jwt token 解析
            Map<String, Object> map = jwtService.parseToken(pure_token);
            System.out.println(map);
            RequestContextHolder.currentRequestAttributes()
                    .setAttribute("uid",map.get("UID"),0);
            return true;
        }
    }
    public static String getCurrentUser(){
        String uid =(String) RequestContextHolder.currentRequestAttributes()
                .getAttribute("uid", 0);
        return uid;
    }


}
